package com.china.produce.handler;

import cn.hutool.core.lang.Assert;
import com.china.produce.annotation.PermissionColumn;
import com.china.produce.handler.ResponseWrite.ResponseWriteHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2025/8/19
 */
@Component
public class ResponsePermissionReturnValueHandler implements HandlerMethodReturnValueHandler {

    @Autowired
    private List<ResponseWriteHandler> responseWriteHandlers;

    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return false;
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

        HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
        Assert.state(response != null, "No HttpServletResponse");
        PermissionColumn permission = returnType.getMethodAnnotation(PermissionColumn.class);
        Assert.state(permission != null, "No @ResponsPermission");
        mavContainer.setRequestHandled(true);
        responseWriteHandlers.stream()
                .filter(handler -> handler.support(returnValue))
                .findFirst()
                .ifPresent(handler -> handler.export(returnValue, response, permission));
    }
}
